﻿using System;
using CardLogistics.Web.Components;
using System.Data;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace CardLogistics.Web.MainPage.SelectPage
{
    public partial class SelReturnBadCard : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //BindDLL(ddlsupName, "basic_suppliers", "suppliersname", "suppliersid", " and STATUS=0 and ISDELETE=0");  //供应商
                GetAPICardTyp();
                BindRpt(1);
            }
        }
        /// <summary>
        /// 获取接口卡类型
        /// </summary>
        private void GetAPICardTyp()
        {
            string apiUrl = HttpGet("http://192.168.0.173:8087/api/logistics/GetCardType");
            DataTable dt = JsonToDataTable(apiUrl.Replace(@"\", ""));
            if (dt != null && dt.Rows.Count > 0)
            {
                ddlsupName.DataSource = dt;
                ddlsupName.DataTextField = "typeName";
                ddlsupName.DataValueField = "typeCode";
                ddlsupName.DataBind();
            }
        }
        /// <summary>
        /// 格式化网站
        /// </summary>
        /// <param name="url">路径</param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "textml, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        #region 将json转换为DataTable
        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');
                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');
                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        #endregion
        /// <summary>
        /// 绑定Rpt数据
        /// </summary>
        private void BindRpt(int pageIndex)
        {


            int recordCount = 0;
            int pageCount = 0;
            StringBuilder sbStr = new StringBuilder();
            //sbStr.Append(" IsSubmit=5 ");
            if (txt_NOName.Text.Trim().Length > 0)
                sbStr.Append(" and (CONNAME like '%" + txt_NOName.Text.Trim() + "%' or CONNO like '%" + txt_NOName.Text.Trim().ToUpper() + "%') ");
            if (ddlsupName.SelectedIndex != 0)
                sbStr.Append(" and SuppId='" + ddlsupName.Value + "'");//供应商
            if (txt_StartData.Text.Trim().Length > 0)
                sbStr.Append(" and to_char(SIGNDATE,'yyyy-MM-dd')>='" + txt_StartData.Text.Trim() + "'");
            if (txt_EndData.Text.Trim().Length > 0)
                sbStr.Append(" and to_char(SIGNDATE,'yyyy-MM-dd')<='" + txt_EndData.Text.Trim() + "'");
            if (Request.QueryString["type"] != null)
            {
                if (Request.QueryString["type"] == "order")
                    sbStr.Append(" and allTotal>dTotal ");
                else if (Request.QueryString["type"] == "cardret")//卡片退货
                    sbStr.Append(" and ID NOT IN (select conid from cardrecovery_returncard  where issubmit!=4 )");//每个合同批次只能退货一次
            }

            DataTable dt = CardLogistics.DAL.CommonData.QuickPage_Oracle("v_purchase_contract_detail", "ID", "  ConNO,BatchNO desc ", WebPageSize, pageIndex, sbStr.ToString(), "*", out pageCount, out recordCount);
            SetNetPagerHtml(AspNetPager1, dt, rptList, recordCount);


            //int recordCount = 0;
            //int pageCount = 0;
            //StringBuilder sbStr = new StringBuilder();
            //sbStr.Append(" IsSubmit=5 ");
            //if (txt_NOName.Text.Trim().Length > 0)
            //    sbStr.Append(" and (CONNAME like '%" + txt_NOName.Text.Trim() + "%' or CONNO like '%" + txt_NOName.Text.Trim().ToUpper() + "%') ");
            //if (ddlsupName.SelectedIndex != 0)
            //    sbStr.Append(" and SuppId='" + ddlsupName.Value + "'");//供应商
            //if (txt_StartData.Text.Trim().Length > 0)
            //    sbStr.Append(" and to_char(SIGNDATE,'yyyy-MM-dd')>='" + txt_StartData.Text.Trim() + "'");
            //if (txt_EndData.Text.Trim().Length > 0)
            //    sbStr.Append(" and to_char(SIGNDATE,'yyyy-MM-dd')<='" + txt_EndData.Text.Trim() + "'");
            //if (Request.QueryString["type"] != null)
            //{
            //    if (Request.QueryString["type"] == "order")
            //        sbStr.Append(" and allTotal>dTotal ");
            //    else if (Request.QueryString["type"] == "cardret")//卡片退货
            //        sbStr.Append(" and ID NOT IN (select conid from cardrecovery_returncard  where issubmit!=4 )");//每个合同批次只能退货一次
            //}

            //DataTable dt = CardLogistics.DAL.CommonData.QuickPage_Oracle("v_purchase_contract_detail", "ID", "  ConNO,BatchNO desc ", WebPageSize, pageIndex, sbStr.ToString(), "*", out pageCount, out recordCount);
            //SetNetPagerHtml(AspNetPager1, dt, rptList, recordCount);
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            WebPageIndex = AspNetPager1.CurrentPageIndex;
            BindRpt(WebPageIndex);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Search_Click(object sender, EventArgs e)
        {
            BindRpt(1);
        }
    }
}